<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<style>
			.input-file{position: absolute; left: 0px; top: 0px; display: inline-block; width: 100%; height: 30px; line-height: 30px; opacity: 0;}
			.datepicker-input{height: 34px; border: 1px solid #D3D3D3; background-color: #fff; border-radius: 2px; width: 250px; padding: 0px 4px;}
		</style>
		<div class="super-theme-example">
			<div class="options-toolbar">
				<form id="deliveryDatagridQueryParams">
					<input id="delivery-storehouseCombo" name="storehouseId" style="width:150px;">
					<input class="easyui-textbox" name="deliveryCode" data-options="width:150,prompt:'发货单号'">
					<select class="easyui-combobox" name="status" style="width:120px;">
					    <option value="">全部状态</option>
					    <option value="0">已创建</option>
					    <option value="10">已派单</option>
					    <option value="20">已发货</option>
					    <option value="30">签收</option>
					    <option value="-20">拒收</option>
					    <option value="-10">取消</option>
					</select>
					<input class="easyui-textbox" name="tel" data-options="width:150,prompt:'收件人电话'">
					<input class="easyui-textbox" name="logisticsCode" data-options="width:150,prompt:'物流单号'">
					<input class="easyui-textbox" name="productId" data-options="width:150,prompt:'产品ID'">
					<input id="delivery-datepicker" class="datepicker-input" />
					<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="delivery.methods.queryDatagrid();">查询</a>
				</form>
				<div class="top-options">
					<a href="javascript:void(0)" class="easyui-menubutton info" data-options="menu:'#delivery_list_tools'">操作</a>
					<div id="delivery_list_tools" style="width:120px;">
						<div data-options="iconCls:'fa fa-plus'" onclick="delivery.methods.createDelivery()">生成发货单</div>
						<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.mgUrlPrefix() + '/admin/delivery/list/export' , delivery.methods.initDatagridQueryParams())">导出发货单-明细</div>
						<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.mgUrlPrefix() + '/admin/delivery/list/exportRow' , delivery.methods.initDatagridQueryParams())">导出发货单-单行</div>
						<div class="menu-sep"></div>
						<div data-options="iconCls:'fa fa-upload'">
							<span class="input-span">上传物流信息</span>
							<input class="input-file" type="file" onchange="delivery.methods.addDelivery(this)" />
						</div>
						<div data-options="iconCls:'fa fa-file-excel-o'">
							<a class="download-link" download="" mce_href="#" href="excel/物流信息模板.xlsx">下载物流信息模板</a>
						</div>
					</div>
				</div>
			</div>
			<table id="delivery-datagrid"></table>
		</div>
		<div id="delivery-skuDetais-window" class="easyui-window" title="详情" style="width:1000px;" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
			<table id="delivery-skuDetais-datagrid" style="height: 400px;"></table>
		</div>
		<script type="text/javascript" src="dists/super/js/xlsx.full.min.js" ></script>
		<script type="text/javascript">
			var delivery = {
				datas : {
				},
				methods: {
					initToobarCombo: function(){
						$('#delivery-storehouseCombo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/storehouse/combo',
						    valueField: 'id',
						    textField: 'text'
						});
					},
					initTimeSelect: function(){
						$('#delivery-datepicker').daterangepicker($.extend(true, {} , globalDaterangepickerOptions));
					},
					initDatagrid: function(){
						$('#delivery-datagrid').datagrid({
							height: $(document).height() - 200,
						    url: commonConfig.mgUrlPrefix() + '/admin/delivery/list',
						    queryParams: {
								begainTime: timestamp($('#delivery-datepicker').val().substring(0, 19)),
								endTime: timestamp($('#delivery-datepicker').val().substring(22))
							},
						    columns:[[
								{field:'deliveryCode',title:'发货单号',width:120,align:'center',formatter: function(value,row,index){
									return '<a onclick="delivery.methods.showDeliveryDetails('+index+');">'+value+'</a>';
								}},
								{field:'statusName',title:'状态',width:60,align:'center'},
								{field:'remark',title:'备注',width:100,align:'center',formatter:function(value,row,index){return value || '--';}},
								{field:'createdAt',title:'创建时间',width:86,align:'center'},
								{field:'consignee',title:'收件人',width:100,align:'center',formatter:function(value,row,index){return '<span>'+ row.consignee +'</span><span class="small-opacity-8">('+ row.tel +')</span>';}},
								{field:'address',title:'地址',width:120,align:'center',formatter:function(value,row,index){return '<span>'+ row.city +'  '+ row.district +'</span><br/><span class="small-opacity-8">'+ row.detail +'</span>';}},
								{field:'storehouseName',title:'配送仓库',width:80,align:'center'},
								{field:'logisticsCode',title:'派送单号',width:80,align:'center',formatter:function(value,row,index){return value || '--';}},
								{field:'deliveryPrice',title:'代收金额',width:80,align:'center'},
								{field:'paymentAmount',title:'汇款金额',width:80,align:'center',formatter:function(value,row,index){return value || '--';}},
								{field:'shippingFreight',title:'物流成本',width:80,align:'center',formatter:function(value,row,index){return value || '--';}},
								{field:'options',title:'操作',width:80,align:'center',formatter:function(value,row,index){
									return '<div class="row-edit-group">' +
												((row.status == 10 || row.status == 0) ? '<a onclick="delivery.methods.deleteDelivery('+index+')">删除</a>' : '') +
										   '</div>';
								}}
						    ]]
						});
					},
					initDatagridQueryParams: function(){
						var params = $('#deliveryDatagridQueryParams').serializeArray();
						var queryParams = {};
						$.each(params , function(index , param){
						     queryParams[param.name] = param.value;
						})
						var time = $('#delivery-datepicker').val();
						queryParams.begainTime = timestamp(time.substring(0, 19));
						queryParams.endTime = timestamp(time.substring(22));
						
						queryParams.deliveryCode = queryParams.deliveryCode.replace(/[\r\n，]/g,",");
						queryParams.tel = queryParams.tel.replace(/[\r\n，]/g,",");
						queryParams.logisticsCode = queryParams.logisticsCode.replace(/[\r\n，]/g,",");
						queryParams.productId = queryParams.productId.replace(/[\r\n，]/g,",");
						
						return queryParams;
					},
					queryDatagrid: function(){
						$('#delivery-datagrid').datagrid('reload',delivery.methods.initDatagridQueryParams());
					},
					showDeliveryDetails: function(index){
						$('#delivery-skuDetais-window').window('open');
						var _prow = $('#delivery-datagrid').datagrid('getRows')[index] ; 
						$('#delivery-skuDetais-datagrid').datagrid({
							url: commonConfig.mgUrlPrefix() + '/admin/delivery/'+_prow.deliveryCode+'/details',
							pagination: false,
						    columns:[[
						    	{field:'productId',title:'产品ID',width:80,align:'center',formatter:function(value,row,index){return '<span>'+row.productId+'</span><br/><span style="opacity: 0.8;">('+row.productSkuBarcode+')</span>';}},
						    	{field:'productTitle',title:'产品名称',width:120,align:'center',formatter:function(value,row,index){return '<span>'+row.productTitle+'</span><br/><span style="opacity: 0.8;">('+row.productSkuName+')</span>';}},
						    	{field:'productImageUrl',title:'产品图片',width:60,align:'center',formatter:function(value,row,index){return '<img class="td-img" src="'+ value +'">';}},
								{field:'quantity',title:'数量',width:60,align:'center'}
						    ]]
						});
					},
					asyncDelivery: function(index){
						requestServer(commonConfig.mgUrlPrefix() + '/admin/delivery/' + $('#delivery-datagrid').datagrid('getRows')[index].deliveryCode + '/async', 'PUT').then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
								delivery.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					createDelivery: function(){
						requestServer(commonConfig.mgUrlPrefix() + '/admin/delivery/generate', 'PUT').then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
								delivery.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					deleteDelivery: function(index){
						$.messager.confirm('提示', '确定删除?', function(r){
							if (r){
								requestServer(commonConfig.mgUrlPrefix() + '/admin/delivery/' + $('#delivery-datagrid').datagrid('getRows')[index].deliveryCode, 'DELETE').then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
										delivery.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					addDelivery: function(e){
						var files = $(e).context.files
						var fileReader = new FileReader()
						if (files.length) {
							fileReader.onload = function (ev) {
								try {
									var workbook = XLSX.read(ev.target.result, {type: 'binary'});
								} catch (e) {
									$.messager.alert('提示',response.message,'error');
									return
								}
								// 创建收货单提交
								delivery.methods.addDeliveryNext(XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]));
								e.value = '' // 清空
							}
							fileReader.readAsBinaryString(files[0]);
						}
					},
					addDeliveryNext: function(paramList){
						var list = [] // 处理后的数据
						for (let i = 0; i < paramList.length; i++) {
							if (paramList[i]['发货单号']) {
								// push 发货单号
								list.push({
									'deliveryCode': paramList[i]['发货单号'],
									'logisticsCode': paramList[i]['物流单号'],
									'logisticsCompany': paramList[i]['代理公司'],
								})
							}
						}
						if(list.length == 0){
							$.messager.alert('提示','上传内容为空','error');
							return ;
						}
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/delivery/send' , 'PUT', list).then((response) => {
							if (response.code == 1) {
								//在这里需要注意操作的情况
								if(response.datas && response.datas.length > 0){
									showErrorMsgs(response.datas , [[{field:'deliveryCode',title:'发货单号',width:60,align:'center'},{field:'logisticsCode',title:'物流单号',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#delivery-datagrid').datagrid('reload');
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
							
						}).catch((error) => {
							console.log(error)
						});
					}
				},
				init : function(){
					delivery.methods.initToobarCombo();
					delivery.methods.initTimeSelect();
					delivery.methods.initDatagrid();
				}
			}
			delivery.init();
		</script>
	</body>
</html>
